<template>
  <div class="news-management">
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :model="searchForm" :inline="true" size="default">
        <el-form-item label="标题">
          <el-input
            v-model="searchForm.title"
            placeholder="请输入新闻标题"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="作者">
          <el-input
            v-model="searchForm.author"
            placeholder="请输入作者"
            clearable
            style="width: 150px"
          />
        </el-form-item>
        <el-form-item label="状态" v-if="userStore.isAdmin">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="待审核" :value="0" />
            <el-option label="已发布" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadNewsList" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮和标签页 -->
    <div class="table-container">
      <div class="table-header">
        <div class="header-left">
          <el-tabs v-model="activeTab" @tab-change="handleTabChange" v-if="userStore.isAdmin">
            <el-tab-pane label="全部动态" name="all">
              <template #label>
                全部动态 <el-badge :value="stats.total" :max="99" />
              </template>
            </el-tab-pane>
            <el-tab-pane label="待审核" name="pending">
              <template #label>
                待审核 <el-badge :value="stats.pending" :max="99" type="warning" />
              </template>
            </el-tab-pane>
          </el-tabs>
          <h3 v-else>我的动态</h3>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showCreateDialog">
            <el-icon><Plus /></el-icon>
            发布动态
          </el-button>
        </div>
      </div>

      <!-- 新闻表格 -->
      <el-table
        :data="newsList"
        v-loading="loading"
        border
        stripe
        class="news-table"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="封面图片" width="100">
          <template #default="{ row }">
            <el-image
              v-if="row.coverImage"
              :src="row.coverImage"
              :preview-src-list="[row.coverImage]"
              preview-teleported
              class="cover-image"
            />
            <span v-else class="no-image">无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="summary" label="简介" min-width="200" show-overflow-tooltip />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="publisherName" label="发布者" width="120" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="viewCount" label="浏览量" width="80" />
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="viewNews(row)">
              查看
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="editNews(row)"
              v-if="canEdit(row)"
            >
              编辑
            </el-button>
            <el-button 
              type="text" 
              size="small" 
              @click="deleteNews(row)"
              class="danger-text"
              v-if="canDelete(row)"
            >
              删除
            </el-button>
            <!-- 管理员审核按钮 -->
            <template v-if="userStore.isAdmin && row.status === 0">
              <el-button type="text" size="small" @click="auditNews(row, 1)" class="success-text">
                通过
              </el-button>
              <el-button type="text" size="small" @click="auditNews(row, 2)" class="danger-text">
                拒绝
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="loadNewsList"
          @current-change="loadNewsList"
        />
      </div>
    </div>

    <!-- 创建/编辑新闻对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑动态' : '发布动态'"
      width="800px"
      :close-on-click-modal="false"
      class="news-dialog"
    >
      <el-form
        ref="newsFormRef"
        :model="newsForm"
        :rules="newsRules"
        label-width="100px"
        size="default"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="newsForm.title" 
            placeholder="请输入新闻标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="作者" prop="author">
          <el-input v-model="newsForm.author" placeholder="请输入作者" />
        </el-form-item>
        
        <el-form-item label="简介" prop="summary">
          <el-input
            v-model="newsForm.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入新闻简介"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        
        <el-form-item label="封面图片">
          <div class="upload-container">
            <el-upload
              :action="uploadUrl"
              :headers="uploadHeaders"
              :show-file-list="false"
              :before-upload="beforeUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              accept="image/*"
            >
              <el-button type="primary" :loading="uploading">
                <el-icon><Upload /></el-icon>
                上传图片
              </el-button>
            </el-upload>
            <div v-if="newsForm.coverImage" class="image-preview">
              <el-image :src="newsForm.coverImage" class="preview-image" />
              <el-button 
                type="danger" 
                size="small" 
                @click="newsForm.coverImage = ''"
                class="remove-btn"
              >
                删除
              </el-button>
            </div>
          </div>
        </el-form-item>
        
        <el-form-item label="内容" prop="content">
          <div class="editor-container">
            <Toolbar
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
              class="editor-toolbar"
            />
            <Editor
              v-model="newsForm.content"
              :defaultConfig="editorConfig"
              mode="default"
              class="editor-content"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitNews">
          {{ isEdit ? '更新' : '发布' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看新闻对话框 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="查看动态"
      width="800px"
      class="view-dialog"
    >
      <div class="news-detail" v-if="currentNews">
        <h2 class="news-title">{{ currentNews.title }}</h2>
        <div class="news-meta">
          <span class="author">作者：{{ currentNews.author }}</span>
          <span class="time">发布时间：{{ formatTime(currentNews.publishTime || currentNews.createTime) }}</span>
          <span class="views">浏览量：{{ currentNews.viewCount }}</span>
        </div>
        <div class="news-summary" v-if="currentNews.summary">
          <strong>摘要：</strong>{{ currentNews.summary }}
        </div>
        <div class="news-cover" v-if="currentNews.coverImage">
          <el-image :src="currentNews.coverImage" class="cover-image-large" />
        </div>
        <div class="news-content" v-html="currentNews.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, shallowRef } from 'vue'
import { useUserStore } from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const uploading = ref(false)
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const isEdit = ref(false)
const newsList = ref([])
const currentNews = ref(null)
const newsFormRef = ref()
const activeTab = ref('all')

// 富文本编辑器
const editorRef = shallowRef()
const toolbarConfig = {
  excludeKeys: ['uploadVideo']
}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: '/api/file/upload/image',
      headers: {
        Authorization: `Bearer ${localStorage.getItem('token')}`
      },
      fieldName: 'file',
      customInsert(res, insertFn) {
        if (res.code === 200) {
          insertFn(res.data.filePath, res.data.fileName)
        } else {
          ElMessage.error('图片上传失败')
        }
      }
    }
  }
}

// 上传配置
const uploadUrl = '/api/file/upload/image'
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 搜索表单
const searchForm = reactive({
  title: '',
  author: '',
  status: null
})

// 分页
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 统计数据
const stats = reactive({
  total: 0,
  pending: 0,
  published: 0,
  rejected: 0
})

// 新闻表单
const newsForm = reactive({
  id: null,
  title: '',
  author: '',
  summary: '',
  content: '',
  coverImage: ''
})

// 表单验证规则
const newsRules = {
  title: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' },
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者', trigger: 'blur' }
  ],
  summary: [
    { required: true, message: '请输入新闻简介', trigger: 'blur' },
    { max: 200, message: '简介长度不能超过200个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入新闻内容', trigger: 'blur' }
  ]
}

// 方法
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD HH:mm')
}

const getStatusType = (status) => {
  const typeMap = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status) => {
  const textMap = {
    0: '待审核',
    1: '已发布',
    2: '已拒绝'
  }
  return textMap[status] || '未知'
}

const canEdit = (row) => {
  // 超级管理员可以编辑所有，企业用户只能编辑自己的
  return userStore.isAdmin || row.publisherId === userStore.userInfo?.id
}

const canDelete = (row) => {
  // 超级管理员可以删除所有，企业用户只能删除自己的
  return userStore.isAdmin || row.publisherId === userStore.userInfo?.id
}

// 添加API导入
import { 
  getNewsList as getNewsListApi, 
  createNews, 
  updateNews, 
  deleteNews as deleteNewsApi,
  auditNews as auditNewsApi,
  getPendingNews 
} from '@/api/news'

const loadNewsList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      page: pagination.page,
      pageSize: pagination.pageSize
    }
    
    let response
    // 根据标签页调整API调用
    if (activeTab.value === 'pending') {
      response = await getPendingNews(params)
    } else {
      response = await getNewsListApi(params)
    }
    
    if (response.code === 200) {
      newsList.value = response.data.list
      pagination.total = response.data.total
      
      // 更新统计数据
      if (activeTab.value === 'all') {
        stats.total = response.data.total
        // 获取各状态统计
        const allResponse = await getNewsListApi({ page: 1, pageSize: 1000 })
        if (allResponse.code === 200) {
          const allNews = allResponse.data.list || []
          stats.pending = allNews.filter(item => item.status === 0).length
          stats.published = allNews.filter(item => item.status === 1).length
          stats.rejected = allNews.filter(item => item.status === 2).length
        }
      }
    }
  } catch (error) {
    ElMessage.error('加载新闻列表失败')
  } finally {
    loading.value = false
  }
}

const submitNews = async () => {
  if (!newsFormRef.value) return
  
  const valid = await newsFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  try {
    submitLoading.value = true
    
    const newsData = {
      ...newsForm,
      publisherId: userStore.userInfo?.id,
      publisherName: userStore.username
    }
    
    let response
    if (isEdit.value) {
      response = await updateNews(newsData)
    } else {
      response = await createNews(newsData)
    }
    
    if (response.code === 200) {
      const message = isEdit.value ? '动态更新成功' : '动态发布成功'
      ElMessage.success(message)
      dialogVisible.value = false
      loadNewsList()
    } else {
      throw new Error(response.message)
    }
  } catch (error) {
    ElMessage.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

const deleteNews = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除动态 "${row.title}" 吗？此操作不可恢复。`,
      '危险操作',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'error'
      }
    )
    
    const response = await deleteNewsApi(row.id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      loadNewsList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const auditNews = async (row, status) => {
  const action = status === 1 ? '通过' : '拒绝'
  try {
    await ElMessageBox.confirm(
      `确定要${action}动态 "${row.title}" 吗？`,
      '审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await auditNewsApi(row.id, { status })
    if (response.code === 200) {
      ElMessage.success(`${action}成功`)
      loadNewsList()
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action}失败`)
    }
  }
}

onMounted(() => {
  loadNewsList()
})

onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy()
  }
})
</script>